#include "Channel.hpp"
#include "Common.hpp"

int main()
{
    // 1. 先有管道
    int pipefd[2] = {0};
    int rn = pipe(pipefd);
    if (rn < 0)
    {
        return PipeError;
    }

    // 2. 创建子进程
    pid_t id = fork();
    if (id < 0) // 创建子进程失败
    {
        return ForkError;
    }

    // 3. 创建信道，写入数据
    if(id == 0)
    {
        ::close(pipefd[1]);

        while(true)
        {
            char buffer[1024];
            int n = ::read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout<<"子进程："<<buffer<<std::endl;
            }
            else if(n == 0)
            {
                exit(0);
            }
            else{}
        }
    }

    // 父进程
    ::close(pipefd[0]);
    std::string buffer("i am father");
    write(pipefd[1],buffer.c_str(),buffer.size());
    sleep(5);

    return 0;
}